package com.allinpay.bizroute.proto;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * @ClassName BizRouteSvr
 * @Description BizRouteSvr 统一服务server
 * @Author richard
 * @Date 2021/12/15 4:24 PM
 */
@Component
@Slf4j
public class BizRouteSvr {

    @Autowired
    private ChkRouteSvc chkRouteSvc;

    @Autowired
    private UpdRouteSvc updRouteSvc;

    @Value("${application.proto.port}")
    private  int port ;

    private Server server;

//    public BizRouteSvr(int port) {
//        this.port = port;
//    }

    //启动服务,并且接受请求
    @PostConstruct
    private void start() throws IOException, InterruptedException {
        //server登记服务
        server = ServerBuilder.forPort(port)
                .addService(chkRouteSvc)
                .addService(updRouteSvc)
                .build().start();
        log.info("BizRouteSvr 服务开始启动-------");

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                log.error("------shutting down gRPC server since JVM is shutting down-------");
                BizRouteSvr.this.stop();
                log.error("------server shut down------");
            }
        });

        BizRouteSvr.this.blockUntilShutdown();

    }

    //stop服务
    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    //server阻塞到程序退出
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}

